package edu.gatech.spacetraderteam3.model;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import edu.gatech.spacetraderteam3.debug.Debug;

/**
 * Utility class for loading/saving.
 * @author Aaron
 * @version 1.0
 */
public class FileManager {

    /**
     * Attempts to save the Player p to the file.	
     * @param p	Player you are saving to file.
     * @return	True if the player was saved, false otherwise.
     */
    public static boolean saveGame(Player p) {
        FileOutputStream file = null;
        ObjectOutputStream out = null;
        try {
            file = new FileOutputStream("saveFile.aaar");
            out = new ObjectOutputStream(file);
            out.writeObject(p);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if(out != null){ // $codepro.audit.disable unnecessaryNullCheck
                	out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (file != null) {
                    file.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * Attempts to load the player from the singular save file.
     * @return	The player that was loaded. If something went wrong, displays a warning message and does NOT crash.
     */
    public static Player loadGame() {
        FileInputStream file = null;
        ObjectInputStream in = null;
        Player player = null;
        try {
            file = new FileInputStream("saveFile.aaar");
            in = new ObjectInputStream(file);
            player = (Player) in.readObject();
        } catch (IOException e) { // $codepro.audit.disable logExceptions
            Debug.writeError("IOException Loading Player!");
        } catch (ClassNotFoundException e2) { // $codepro.audit.disable logExceptions
            Debug.writeError("ClassNotFoundException Loading Player!");
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (file != null) {
                    file.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return player;
    }

    /**
     * String representation of FileManager class. Should never see this.
     * @return A succinct warning.
     */
    public String toString() {
        return "File Manager! You shouldn't be seeing this...";
    }

}
